package changedb;


import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Serializer;

/**
 *
 *
 * @author Ben Goodwin
 * @version @version 2.0 16/09/2011
 */
public class Save {

    private static File currentFile;
    private static String[] headers = {"type", "firstName", "surname", "email",
        "mobile", "dobD", "dobM", "dobY", "address1", "address2", "city",
        "postcode", "mother", "father", "school", "sosNum", "medical", "other"};
    private static boolean encrypt;

    public static boolean save(File currentFile, MembersList ml, boolean encrypt) {
        ArrayList<Member> members = (ArrayList) ml.getMembers();
        Builder builder = new Builder();
        Element root;
        try {
            Document data = builder.build(currentFile);
            root = data.getRootElement();
        if(root.getLocalName().equals("databaseEncrypted")) encrypt = true;
        } catch (Exception ex) {}
        if (encrypt) root = new Element("databaseEncrypted");
        else root = new Element("database");
        for (Member m : members) {
            Element member = new Element("member");
            root.appendChild(member);
            ArrayList<String> details = (ArrayList) m.getDetails();
            for (int index = 0; index < headers.length; index++) {
                Element e = new Element(headers[index]);
                if (encrypt) {
                    e.appendChild(x.encrypt(details.get(index)));
                } else {
                    e.appendChild(details.get(index));
                }
                member.appendChild(e);
            }
        }
        Document doc = new Document(root);
        try {
            Serializer serializer = new Serializer((OutputStream) new FileOutputStream(currentFile), "UTF-8");
            serializer.setIndent(4);
            serializer.write(doc);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    public static boolean saveAs(MembersList ml, boolean encrypt) {
        JFileChooser save = new JFileChooser();
        save.setFileFilter(new XMLFilter());
        int choose = save.showSaveDialog(null);
        if (choose == JFileChooser.APPROVE_OPTION) {
            currentFile = save.getSelectedFile();
            if (!(currentFile.getPath().toLowerCase().endsWith(".xml"))) {
                String name = currentFile.getPath();
                String newName = name + ".xml";
                currentFile = new File(newName);
                return save(currentFile, ml, encrypt);
            }
        }
        return false;
    }
}
